import tornado.web
from tornado.options import options, define
from sqlalchemy.engine.url import URL
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from custom.JsonEncoder import JsonEncoder
from utils.wechat.manager import TokenManager
import settings.config
from routes import urls
define('config', default='development', type=str)
config = settings.config.load_config(options.config)
mysql_conn_url = URL(
        drivername='mysql',
        username=config.MYSQL['username'],
        password=config.MYSQL['password'],
        host=config.MYSQL['host'],
        port=config.MYSQL['port'],
        database=config.MYSQL['database'],
        query={'charset': config.MYSQL['charset']}
    )

handlers = ()
handlers += urls.url_pattern
handlers += tuple((x[0], tornado.web.StaticFileHandler, x[1]) for x in config.STATIC_PATH)


class Application(tornado.web.Application):
    def __init__(self):
        _settings = dict(
            template_path=config.TEMPLATE_PATH,
            debug=config.DEBUG,
            cookie_secret=config.COOKIE_SECRET,
            login_url=config.LOGIN_URL
        )
        tornado.web.Application.__init__(self, handlers, **_settings)
        engine = create_engine(mysql_conn_url, encoding=config.MYSQL['charset'], echo=config.DEBUG)
        self.db = scoped_session(sessionmaker(bind=engine))
        from models import Base, init_db
        init_db(Base, engine)
        self.json_encoder = JsonEncoder(Base)
        self.wx_token_manager = TokenManager()


def create_application():
    application = Application()
    print(config.PORT)
    application.listen(config.PORT)
